package com.medical.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.medical.dao.AuthenticationCashMapper;
import com.medical.dao.AuthenticationCertificateMapper;
import com.medical.dao.AuthenticationLanguageMapper;
import com.medical.dao.AuthenticationSchoolMapper;
import com.medical.dao.AuthenticationStudyingMapper;
import com.medical.dao.CollectMapper;
import com.medical.dao.InterpreterAuthenticationMapper;
import com.medical.dao.InterpreterAuthenticationTerritoryMapper;
import com.medical.dao.InterpreterMapper;
import com.medical.dao.InterpreterOrderEvaluateMapper;
import com.medical.dao.InterpreterOrderMapper;
import com.medical.dao.LanguageMapper;
import com.medical.dao.UserMapper;
import com.medical.entity.Collect;
import com.medical.entity.Interpreter;
import com.medical.entity.InterpreterAuthentication;
import com.medical.entity.Language;
import com.medical.entity.MyException;
import com.medical.entity.ResultBean;
import com.medical.entity.User;
import com.medical.service.InterpreterService;
import com.medical.util.DataUtil;
import com.medical.util.LocationUtils;


@Service
@Transactional
public class InterpreterServiceImpl implements InterpreterService {
	@Resource
	private InterpreterMapper dao;
	
	@Resource
	private InterpreterOrderEvaluateMapper ieDao;
	
	@Resource
	private LanguageMapper laDao;
	
	@Resource
	private CollectMapper cDao;
	
	@Resource
	private UserMapper uDao;
	
	@Resource
	private AuthenticationLanguageMapper aclDao;
	
	@Resource
	private AuthenticationCertificateMapper acfDao;
	
	@Resource
	private AuthenticationSchoolMapper acsDao;
	
	@Resource
	private AuthenticationStudyingMapper asDao;
	
	@Resource
	private AuthenticationCashMapper acDao;
	
	@Resource
	private InterpreterAuthenticationTerritoryMapper iatDao;
	
	@Resource
	private InterpreterOrderMapper ioDao;
	
	@Resource
	private InterpreterAuthenticationMapper iaDao;
	
	@Override
	public ResultBean<Integer> addInterpreter(Interpreter ine) {
		// TODO Auto-generated method stub
		try {
			int type=0;
			if(ine.getInterpretertype()==4) {
				type=1;
			}else {
				type=2;
			}
			InterpreterAuthentication in=iaDao.getByUserid(ine.getUserid(), type);
			if(in==null) {
				return new ResultBean<>(new MyException("未认证"));
			}
			if(in.getStates()!=2) {
				return new ResultBean<>(new MyException("认证未通过"));
			}
			ine.setStates(1);
			ine.setTime(new Date());
			ine.setRelease(true);
			int count=dao.insert(ine);
			if(count>0) {
				return new ResultBean<>(ine.getId());
			}else {
				return new ResultBean<>(new MyException("添加异常"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(new MyException("系统异常"));
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> selectByInter(Interpreter ite, Integer pricetype,String interpretAge,String ages,String prices, int score,String nationality,Integer pageIndex,Double longitude,Double latitude,int size,String keyword) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" where 1=1 and i.name like '%"+keyword+"%' ");
		if(ite.getTranslatelanguage()!=null&&ite.getTranslatelanguage()!=0) {
			whereSql.append(" and i.translatelanguage="+ite.getTranslatelanguage());
		}
		if(ite.getIntolanguage()!=null&&ite.getIntolanguage()!=0) {
			whereSql.append(" and i.intolanguage="+ite.getIntolanguage());
		}
		if(ite.getTranslategrade()!=null&&!ite.getTranslategrade().equals("")) {
			whereSql.append(" and i.translategrade='"+ite.getTranslategrade()+"'");
		}
		if(ite.getIntograde()!=null&&!ite.getIntograde().equals("")) {
			whereSql.append(" and i.intograde='"+ite.getIntolanguage()+"'");
		}
		if(ite.getInterpretertype()!=null&&ite.getInterpretertype()!=0) {
			whereSql.append(" and i.interpretertype="+ite.getInterpretertype());
		}
		if(pricetype!=null&&pricetype!=0) {
			if(prices!=null&&!prices.equals("")) {
				String[] price=prices.split("-");
				if(pricetype==1) {
					whereSql.append(" and i.hourprice>="+price[0]+" and i.hourprice<="+price[1]);
				}else if(pricetype==2) {
					whereSql.append(" and i.minuteprice>="+price[0]+" and i.minuteprice<="+price[1]);
				}else if(pricetype==3) {
					whereSql.append(" and i.wordprice>="+price[0]+" and i.wordprice<="+price[1]);
				}
			}
		}
		
		if(ite.getAddress()!=null&&!ite.getAddress().equals("")) {
			whereSql.append(" and i.address='"+ite.getAddress()+"'");
		}
		if(ite.getSex()!=null) {
			whereSql.append(" and i.sex="+ite.getSex());
		}
/*		if(ite.getAddress()!=null&&!ite.getAddress().equals("")) {
			whereSql.append("and i.address='"+ite.getAddress()+"'");
		}*/
		if(ite.getEducation()!=null&&!ite.getEducation().equals("")) {
			whereSql.append(" and i.education='"+ite.getEducation()+"'");
		}
		if(ages!=null&&!ages.equals("")) {
			String[] age=ages.split("-");
			whereSql.append(" and (DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(ia.birthdate)), '%Y')+0 )>="+age[0]+" and (DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(ia.birthdate)), '%Y')+0 )<="+age[1]);
		}
		
		if(interpretAge!=null&&!interpretAge.equals("")) {
			String[] age=interpretAge.split("-");
			whereSql.append(" and i.age>="+age[0]+" and i.age<="+age[1]);
		}
		if(ite.getExperience()!=null&&!ite.getExperience().equals("")) {
			whereSql.append(" and i.experience='"+ite.getExperience()+"'");
		}
		/*if(ite.getCertificateid()!=null&&ite.getCertificateid()!=0) {
			whereSql.append("and i.certificateid="+ite.getCertificateid());
		}*/
		if(ite.getExperienceid()!=null&&ite.getExperienceid()!=0) {
			whereSql.append(" and i.experienceid="+ite.getExperienceid());
		}
		if(ite.getTerritoryid()!=null&&ite.getTerritoryid()!=0) {
			whereSql.append(" and i.territoryid="+ite.getTerritoryid());
		}
		if(nationality!=null&&!nationality.equals("")) {
			whereSql.append(" and u.nationality='"+nationality+"'");
		}
		whereSql.append(" and i.states=2 and i.release=true");
		String orderStr="";
		if(score==1) {   //默认
			orderStr=" order by i.time desc";
		}else if(score==2) {    //价格
			orderStr=" order by i.hourprice";
		}
		try {
			List<Map<String, Object>> list=dao.selectByInter(whereSql.toString(), orderStr,(pageIndex-1)*size,size);
			List<Map<String, Object>> list1=new ArrayList<>();
			for(Map<String, Object> map:list) {
				Double longitude1=Double.valueOf(map.get("longitude").toString());
				Double latitude1=Double.valueOf(map.get("latitude").toString());
				Double ju=LocationUtils.getDistance(latitude, longitude, latitude1, longitude1);
				map.put("ju", ju);
				Integer interpreterid=Integer.valueOf(map.get("id").toString());
				Double fen=ieDao.selectAvgScore(interpreterid);
				map.put("fen", fen);
				Integer translatelanguage=Integer.valueOf(map.get("translatelanguage").toString());
				Integer intolanguage=Integer.valueOf(map.get("intolanguage").toString());
				Language la=laDao.selectById(translatelanguage);
				map.put("translatelanguageName", la.getLanguage());
				la=laDao.selectById(intolanguage);
				map.put("intolanguageName", la.getLanguage());
				list1.add(map);
			}
			if(score==3) {   //距离
				
				 Collections.sort(list1, new Comparator<Map<String, Object>>() {
			            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			            	Double name1 = Double.parseDouble(o1.get("ju").toString()) ;//name1是从你list里面拿出来的一个 
			            	Double name2 = Double.parseDouble(o2.get("ju").toString()) ; //name1是从你list里面拿出来的第二个name
			                return name1.compareTo(name2);
			            }
			        });
			}else if(score==4){  //人气
				
				 Collections.sort(list1, new Comparator<Map<String, Object>>() {
			            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			            	Double name1 = Double.valueOf(o1.get("fen").toString()) ;//name1是从你list里面拿出来的一个 
			            	Double name2 = Double.valueOf(o2.get("fen").toString()) ; //name1是从你list里面拿出来的第二个name
			                return name2.compareTo(name1);
			            }
			        });
			}
			return new ResultBean<>(list1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<Map<String, Object>> selectById(int id, int userId) {
		// TODO Auto-generated method stub
		try {
			Map<String, Object> map=new HashMap<>();
			Interpreter in=dao.selectById(id);
			map.put("Interpreter", in);
			Language translatelanguage=laDao.selectById(in.getTranslatelanguage());
			Language intolanguage=laDao.selectById(in.getIntolanguage());
			map.put("translatelanguage", translatelanguage);
			map.put("intolanguage", intolanguage);
			User user=uDao.selectById(in.getUserid());
			List<Collect> list=cDao.selectList(new EntityWrapper<Collect>().eq("userid", userId).and().eq("collecttype", 2).and().eq("collectid", id));
			if(list.size()>0) {
				map.put("isCollect", true);
			}else {
				map.put("isCollect", false);
			}
			map.put("user", user);
			int type=0;
			if(in.getInterpretertype()==4) {
				type=1;
			}else {
				type=2;
			}
			InterpreterAuthentication ia=iaDao.getByUserid(user.getId(), type);
			int age=DataUtil.getAgeByBirth(ia.getBirthdate());
			map.put("nianling", age);
			List<Map<String, Object>> la=aclDao.selectByAuthenticationid(ia.getId(),2);
			map.put("lanuage", la);
			map.put("certificate", acfDao.selectByAuthenticationid(ia.getId(),2));
			map.put("school", acsDao.selectByAuthenticationid(ia.getId(),2));
			map.put("studying", asDao.selectByAuthenticationid(ia.getId(),2));
			map.put("territory", iatDao.selectByAuthenticationid(ia.getId()));
			map.put("InterpreterAuthentication", ia);
			int fuNum=ioDao.fuCount(id);
			map.put("fuNum", fuNum);
			Integer jiao=acDao.selectStates(user.getId());
			if(jiao!=null) {
				if(jiao==1) {
					map.put("isJiao", true);
				}else {
					map.put("isJiao", false);
				}
			}else {
				map.put("isJiao", false);
			}
			Double fen=ieDao.selectAvgScore(userId);
			map.put("fen", fen);
			return new  ResultBean<Map<String,Object>>(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<List<Map<String,Object>>> findHotInterpreters() {
		// TODO Auto-generated method stub
		List<Map<String,Object>> interpreterList= dao.selectByTop();
		return  new ResultBean<>(interpreterList);
	}

	@Override
	public ResultBean<Integer> selectByInterCount(Interpreter ite, Integer pricetype, String ages, String prices,
			int score, String nationality, String keyword) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" where 1=1 and i.name like '%"+keyword+"%' ");
		if(ite.getTranslatelanguage()!=null&&ite.getTranslatelanguage()!=0) {
			whereSql.append(" and i.translatelanguage="+ite.getTranslatelanguage());
		}
		if(ite.getIntolanguage()!=null&&ite.getIntolanguage()!=0) {
			whereSql.append(" and i.intolanguage="+ite.getIntolanguage());
		}
		if(ite.getTranslategrade()!=null&&!ite.getTranslategrade().equals("")) {
			whereSql.append(" and i.translategrade='"+ite.getTranslategrade()+"'");
		}
		if(ite.getIntograde()!=null&&!ite.getIntograde().equals("")) {
			whereSql.append(" and i.intograde='"+ite.getIntolanguage()+"'");
		}
		if(ite.getInterpretertype()!=null&&ite.getInterpretertype()!=0) {
			whereSql.append(" and i.interpretertype="+ite.getInterpretertype());
		}
		if(pricetype!=null&&pricetype!=0) {
			if(prices!=null&&!prices.equals("")) {
				String[] price=prices.split("-");
				if(pricetype==1) {
					whereSql.append(" and i.hourprice>="+price[0]+" and i.hourprice<="+price[1]);
				}else if(pricetype==2) {
					whereSql.append(" and i.minuteprice>="+price[0]+" and i.minuteprice<="+price[1]);
				}else if(pricetype==3) {
					whereSql.append(" and i.wordprice>="+price[0]+" and i.wordprice<="+price[1]);
				}
			}
		}
		
		if(ite.getAddress()!=null&&!ite.getAddress().equals("")) {
			whereSql.append(" and i.address='"+ite.getAddress()+"'");
		}
		if(ite.getSex()!=null) {
			whereSql.append(" and i.sex="+ite.getSex());
		}
/*		if(ite.getAddress()!=null&&!ite.getAddress().equals("")) {
			whereSql.append("and i.address='"+ite.getAddress()+"'");
		}*/
		if(ite.getEducation()!=null&&!ite.getEducation().equals("")) {
			whereSql.append(" and i.education='"+ite.getEducation()+"'");
		}
		if(ages!=null&&!ages.equals("")) {
			String[] age=ages.split("-");
			whereSql.append(" and i.age>="+age[0]+" and i.age<="+age[1]);
		}
		if(ite.getExperience()!=null&&!ite.getExperience().equals("")) {
			whereSql.append(" and i.experience='"+ite.getExperience()+"'");
		}
		/*if(ite.getCertificateid()!=null&&ite.getCertificateid()!=0) {
			whereSql.append("and i.certificateid="+ite.getCertificateid());
		}*/
		if(ite.getExperienceid()!=null&&ite.getExperienceid()!=0) {
			whereSql.append(" and i.experienceid="+ite.getExperienceid());
		}
		if(ite.getTerritoryid()!=null&&ite.getTerritoryid()!=0) {
			whereSql.append(" and i.territoryid="+ite.getTerritoryid());
		}
		if(nationality!=null&&!nationality.equals("")) {
			whereSql.append(" and u.nationality='"+nationality+"'");
		}
		whereSql.append(" and i.states=2 and i.release=true");
		int count=dao.selectByInterCount(whereSql.toString());
		return new ResultBean<Integer>(count);
	}

}
